package nl.arjanfrans.stopwatch.main;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by arjan on 7/12/13.
 */
public class Stopwatch {
    private long start_time;
    private long stop_time;
    private long pause_time;
    private boolean paused;
    private ArrayList<Long[]> laps;

    public Stopwatch() {
        reset();
    }

    public void start() {
        if(paused) {
            pause_time = getElapsedTime();
            stop_time = 0;
            start_time = System.currentTimeMillis();
            paused = false;
        }
    }

    public void pause() {
        if(!paused) {
            stop_time = System.currentTimeMillis();
            paused = true;
        }
    }

    public void reset() {
        laps = new ArrayList<Long[]>();
        start_time = 0;
        stop_time = 0;
        pause_time = 0;
        paused = true;
    }

    public Long[] addLap() {
        Long[] lap = new Long[3];
        lap[0] = getElapsedTime();
        if(!laps.isEmpty()) {
            lap[1] = lap[0] - laps.get(laps.size()-1)[0];
        }
        else {
            lap[1] = lap[0];
        }
        lap[2] = (long) laps.size()+1;
        laps.add(lap);
        return laps.get(laps.size()-1);
    }

    public ArrayList<Long[]> getLaps() {
        return laps;
    }

    public long getElapsedTime() {
        if(paused) {
            return (stop_time - start_time) + pause_time;
        }
        else {
            return (System.currentTimeMillis() - start_time) + pause_time;
        }
    }

    public String getTimeText() {
        long millis = getElapsedTime();
        return convertToText(millis);
    }

    public String convertToText(long millis) {
        int hours = (int) (millis / 3600000);
        int minutes = (int) (millis % 3600000) / 60000;
        int seconds = (int) ((millis % 360000) % 60000) / 1000;
        int milliseconds = (int) (millis % 1000);
        return String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, milliseconds);
    }

    public boolean isPaused() {
        return paused;
    }




}
